package com.siki.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.siki.dto.DepartmentDTO;
import com.siki.dto.PageQueryUserDTO;
import com.siki.dto.SaveDepartmentInfoDTO;
import com.siki.dto.SaveDepartmentInfoListDTO;
import com.siki.dto.UserDTO;
import com.siki.dao.DepartmentInformationMapper;
import com.siki.dao.UserMapper;
import com.siki.pojo.enumerate.ResultType;
import com.siki.pojo.model.DepartmentInformation;
import com.siki.pojo.model.User;
import com.siki.service.UserService;
import com.siki.vo.UserListInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityNotFoundException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author Siki
 * @Date 2020/3/2
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DepartmentInformationMapper departmentInformationMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertUser(UserDTO dto) {
        //判断数据库中有没有这个数据
        boolean flag = false;
        User user = null;
        if (verUserInfo(dto.getNumber()) != null) {
            user = verUserInfo(dto.getNumber());
            flag = true;
        } else {
            user = new User();
            user.setId(UUID.randomUUID().toString());
            user.setCreateTime(new Date());
            user.setName(dto.getName());
            user.setUserSex(dto.getUserSex());
            user.setSelfIntroduction(dto.getSelfIntroduction());
            user.setRemark(dto.getRemark());
            user.setPhone(dto.getPhone());
            user.setWeChat(dto.getWeChat());
            user.setNumber(dto.getNumber()); //学号
            user.setClassInfo(dto.getClassInfo());
            user.setEmail(dto.getEmail());
            user.setAvatarUrl(dto.getAvatarUrl());
        }
        if (flag == true) {
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("self_introduction", dto.getSelfIntroduction()).set("create_time", new Date())
                    .set("remark", dto.getRemark()).set("phone", dto.getPhone()).set("we_chat", dto.getWeChat())
                    .set("email", dto.getEmail()).set("avatar_url", dto.getAvatarUrl()).eq("id", user.getId());

            userMapper.update(user, updateWrapper);
            QueryWrapper<DepartmentInformation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", user.getId());
            departmentInformationMapper.selectList(queryWrapper).stream().forEach(departmentInformation -> {
                departmentInformationMapper.deleteById(departmentInformation.getId());
            });
        } else {
            System.out.println(user.getName()+","+ LocalDateTime.now().
                    format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))+" 提交");
            userMapper.insert(user);
        }
        List<DepartmentInformation> departmentInformations = new ArrayList<>();
        for (DepartmentDTO d :
                dto.getIntention()) {
            DepartmentInformation departmentInformation = new DepartmentInformation();
            departmentInformation.setNo(d.getNo());
            departmentInformation.setPost(d.getPost());
            departmentInformation.setResultType(Enum.valueOf(ResultType.class, "NOTYET"));
            departmentInformation.setUserId(user.getId());
            departmentInformation.setDepartmentInfo(d.getDepartmentInfo());
            departmentInformations.add(departmentInformation);
        }
        departmentInformationMapper.insertListDepartment(departmentInformations);
    }

    @Override
    public Page<UserListInfoVO> PageSelectUserList(PageQueryUserDTO dto) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(dto.getSelectedGroup()) || !dto.getSelectedGroup().equals("")) {
            Optional.ofNullable(dto.getSelectedGroup()).ifPresent(s -> {
                queryWrapper.eq("gdi.department_info", s);
            });
        }
        if (dto.getOnlyPass() == true) {
            queryWrapper.eq("gdi.result_type", "PASS");
        }
        Page<UserListInfoVO> page = new Page<>(dto.getPageNum() == null ? 1 : dto.getPageNum(), dto.getPageSize() == null ? 10 : dto.getPageSize());
        return page.setRecords(userMapper.queryUserByEq(page, queryWrapper).stream().map(UserListInfoVO::new).collect(Collectors.toList()));
    }

    @Override
    public User getUser(String userId) {
        return Optional.ofNullable(userMapper.selectById(userId))
                .orElseThrow(() -> new EntityNotFoundException("该id:" + userId + "指定user不存在"));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public User saveDepartmentInfo(SaveDepartmentInfoListDTO dto) {
        List<SaveDepartmentInfoDTO> saveDepartmentInfoDTOS = dto.getSaveDepartmentInfoDTOS();
        for (SaveDepartmentInfoDTO saveDepartmentInfoDTO :
                saveDepartmentInfoDTOS) {
            DepartmentInformation department_Information = departmentInformationMapper.selectById(saveDepartmentInfoDTO.getId());
            UpdateWrapper<DepartmentInformation> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("remark", saveDepartmentInfoDTO.getRemark())
                    .set("result_type",saveDepartmentInfoDTO.getResultType())
                    .set("score",saveDepartmentInfoDTO.getScore())
                    .eq("id", saveDepartmentInfoDTO.getId());
            departmentInformationMapper.update(department_Information,updateWrapper);
        }
        var user = getUser(dto.getUserId());
        return user;
    }

    @Override
    public void delete(String id) {
        User user = getUser(id);
        user.getDepartmentInformationList().forEach(departmentInformation -> {
            departmentInformationMapper.deleteById(departmentInformation.getId());
        });
        userMapper.deleteById(id);
    }

    private User verUserInfo(String number) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("number", number);
        User user = userMapper.selectOne(queryWrapper);
        return user;
    }
}